package jhunter.web.mvc.view;

import java.io.IOException;
import java.util.Collection;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jhunter.template.TemplateLoader;
import jhunter.web.mvc.ActionContext;
import jhunter.web.mvc.form.FormRender;
import jhunter.web.mvc.form.VelocityFormRender;
import jhunter.web.mvc.params.FlashManger;
import jhunter.web.mvc.params.FlashMap;

import org.apache.commons.lang.StringUtils;

public class DefaultViewResovle implements ViewResovle {

	private FormRender formRender = new VelocityFormRender();
//	
//	private String resovleJspPath(String base, String path) {
//		StringBuilder sb = new StringBuilder("/WEB-INF/jsp");
//		if (base != null) {
//			if (!base.startsWith("/")) {
//				sb.append("/");
//			}
//			sb.append(base);
//			if (!base.endsWith("/")) {
//				sb.append("/");
//			}
//		}
//		if (!path.startsWith("/") && !sb.toString().endsWith("/")) {
//			sb.append("/");
//		}
//		sb.append(path);
//		sb.append(".jsp");
//		return sb.toString();
//	}

	@Override
	public void render(Object result, FlashManger flashManger, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		ActionContext ac = ActionContext.getContext();
		if (result instanceof CharSequence) {
			// jsp
			// @:
			String r = result.toString();
			if (r.startsWith("@:")) {
				response.getWriter().print(r.substring(2));
//				response.setContentType("application/json;charset=UTF-8");
				response.getWriter().flush();
				response.getWriter().close();
			} else if (r.startsWith("r:")) {
				String path = r.substring(2);
				FlashMap flash = ac.getFlash();
				if (flash != null && flash.size() > 0) {
					flash.setRequestUri(path);
					flashManger.saveOutputFlashMap(flash, request, response);
				}
				response.sendRedirect(path);
			} else if(r.startsWith("form:")) {
				String formName = r.substring("form:".length());
				if(StringUtils.isEmpty(formName)) {
					formName = ac.getActionConfig().getAction().getName();
				}
				formRender.render(formName, request, response) ;
			}else if(r.startsWith("jsp:")){
//				request.setAttribute("params", ac.getParameters());
//				request.setAttribute("session", ac.getSession());
//				request.setAttribute("application", ac.getApplication());
//				request.setAttribute("flash", ac.getFlash());
//				Map<String, Object> atts = ac.getAttributes();
//				if (atts != null) {
//					for (String key : atts.keySet()) {
//						request.setAttribute(key, atts.get(key));
//					}
//				}
//				request.getRequestDispatcher(resovleJspPath(jspbathPath, r)).forward(request, response);
			}else {
				ac.getActionConfig().renderTemplate(r,request, response);
			}
		} else if (result instanceof Collection) {

		}
	}

}
